package com.powernode.filter;

import com.alibaba.excel.event.Order;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.config.WhiteUrlsConfig;
import com.powernode.constant.AuthConstants;
import com.powernode.constant.BusinessEnum;
import com.powernode.constant.HttpConstants;
import com.powernode.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
 * 全局token过滤器
 * 前后端约定好令牌存放的位置：请求头的Authorization bearer token
 */

@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Order {

    @Autowired
    private WhiteUrlsConfig whiteUrlsConfig;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();

        //获取请求路径
        String path = request.getPath().toString();
        //获取白名单路径并对比路径是否放行
        if (whiteUrlsConfig.getAllowUrls().contains(path)) {

            //符合白名单，进行放行
            return chain.filter(exchange);
        }

        //不符合放行规则，获取请求头中的 Authorization
        String authorization = request.getHeaders().getFirst(AuthConstants.AUTHORIZATION);

        //判断是否有值
        if (StringUtils.hasText(authorization)) {
            // Authorization 格式为 ：bearer xxxxxxx  所以进行替换
            String tokenValue = authorization.replace(AuthConstants.BEARER, "");

            //判断token值是否存在redis中并且有效
            if (StringUtils.hasText(tokenValue) && stringRedisTemplate.hasKey(AuthConstants.LOGIN_TOKEN_PREFIX + tokenValue)) {
                //验证通过，放行
                return chain.filter(exchange);
            }

        }
        //验证失败
        log.error("拦截非法请求，时间:{}，请求API路径为:{}", new Date(), path);

        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置响应头
        response.getHeaders().set(HttpConstants.CONTENT_TYPE, HttpConstants.APPLICATION_JSON);

        //设置响应信息
        Result<Object> result = Result.fail(BusinessEnum.UN_AUTHORIZATION);

        //创建一个objectMapper对象
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] bytes = new byte[0];
        try {
            bytes = objectMapper.writeValueAsBytes(result);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
        Mono<Void> voidMono = response.writeWith(Mono.just(dataBuffer));

        return voidMono;
    }


    @Override
    public int order() {
        return -5;
    }

}
